import { Injectable, Injector } from '@angular/core';
import { MessagerService } from '@farris/ui-messager';
import { NotifyService } from '@farris/ui-notify';
import { EventEditorService, DomService, RefreshFormService, DesignViewModelService, FormComponentType, FormViewModel, WebCmdService } from '@farris/designer-services';
import { DgControl } from '../../../../../utils/dg-control';
import { ControlContextMenuItem } from '../../../../../entity/control-context-menu';
import { ControlService } from '../../../../../service/control.service';
import { FarrisDesignBaseComponent } from '@farris/designer-element';
import { IdService } from '@farris/ui-common';
import { cloneDeep } from 'lodash-es';

const DATAGRID_Edit_IN_CARD_COMMAND = 'editInCard';
const DATAGRID_Edit_IN_SIDEBAR_COMMAND = 'EditInSidebarCard';
const DATAGRID_Edit_IN_MODAL_COMMAND = 'EditInModalCard';

/**
 * 子表启用弹窗编辑/侧边栏编辑构造实体类
 */
export class CreateModalCardBuildInfo {
    /** 弹窗组件id */
    componentId: string;
    /** 组件id后缀 */
    componentIdPrefix: string;
    /** 组件展示名称 */
    componentName: string;
    /** 组件类型 */
    componentType: string;
    /** 组件样式 */
    componentAppearance: string;

    /** 列表组件的列 */
    selectedFields: any[];
    /** 列表组件的数据源 */
    dataSource: string;

    /** 列表组件的ViewModelId */
    gridViewModelId: string;

    /** 列表组件的ComponenentId */
    gridComponentId: string;

    /** 展示方式：弹窗|侧边栏 */
    showType: 'modal' | 'sidebar';
}

/**
 * 列表启用/移除侧边栏编辑、弹出卡片式编辑相关服务
 */
export class DataGridEditByCardContextMenuService {
    private domService: DomService;
    private messagerService: MessagerService;
    public refreshFormService: RefreshFormService;
    private notifyService: NotifyService;
    private controlService: ControlService;
    private dgVMService: DesignViewModelService;
    private webCmdService: WebCmdService;
    private eventEditorService: EventEditorService;

    // 按钮命令
    btnCommand = {
        Add: 'ModalAddItem1',
        Remove: 'ModalRemoveItem1',
        Cancel: 'ModalCancel1',
        Save: 'ModalConfirm1',
        SaveAndClose: 'ModalConfirmAndClose1',
        Load: 'ModalLoad1',
        LoadAndAdd: 'ModalLoadAndAdd1',
        LoadAndEdit: 'ModalLoadAndEdit1',
        LoadAndView: 'ModalLoadAndView1',
        PopUpEdit: 'ModalPopUpEdit1',
        PopUpAdd: 'ModalPopUpAdd1'
    };
    /** 弹窗命令所属构件id。构件在webcmp包中 */
    popUpCmpId = '8d21e69c-70b3-44f6-88b5-fd6a8d3ce11b';

    /** 创建组件所需的构造信息 */
    buildInfo: CreateModalCardBuildInfo;

    constructor(
        private injector: Injector, private controlCreatorService: any) {
        this.domService = this.injector.get(DomService);
        this.notifyService = this.injector.get(NotifyService);
        this.refreshFormService = this.injector.get(RefreshFormService);
        this.controlService = this.injector.get(ControlService);
        this.messagerService = this.injector.get(MessagerService);
        this.dgVMService = this.injector.get(DesignViewModelService);
        this.webCmdService = this.injector.get(WebCmdService);
        this.eventEditorService = this.injector.get(EventEditorService);
    }

    assembleCardEditMenu(menuConfig: ControlContextMenuItem[], dataGridInstance: FarrisDesignBaseComponent) {
        const multiViewMenu = menuConfig.find(menu => menu.category === DATAGRID_Edit_IN_CARD_COMMAND);
        if (!multiViewMenu) {
            return menuConfig;
        }
        // 只支持子表
        const viewModel = this.domService.getViewModelById(dataGridInstance.viewModelId);
        if (viewModel.bindTo === '/') {
            menuConfig = menuConfig.filter(menu => menu.category !== DATAGRID_Edit_IN_CARD_COMMAND);
            return menuConfig;
        }

        // 父级要有f-grid-is-sub样式，否则设计器显示卡片面板有高度样式问题---暂时用样式来判断，后续看能否优化，或者是否能通过模板来判断
        const parentCmpSchema = dataGridInstance.parent && dataGridInstance.parent.component;
        if (parentCmpSchema && parentCmpSchema.appearance && parentCmpSchema.appearance.class && !parentCmpSchema.appearance.class.includes('f-grid-is-sub')) {
            menuConfig = menuConfig.filter(menu => menu.category !== DATAGRID_Edit_IN_CARD_COMMAND);
            return menuConfig;
        }

        const modalEditMenu = menuConfig.find(menu => menu.id === DATAGRID_Edit_IN_MODAL_COMMAND);
        const sidebarMenu = menuConfig.find(menu => menu.id === DATAGRID_Edit_IN_SIDEBAR_COMMAND);
        const enableEditByCard = dataGridInstance.component.enableEditByCard;
        switch (enableEditByCard) {
            // 已启用弹出编辑
            case 'modal': {
                modalEditMenu.id = 'Disable' + modalEditMenu.id;
                modalEditMenu.title = '关闭' + modalEditMenu.title;

                sidebarMenu.id = 'Enable' + sidebarMenu.id;
                sidebarMenu.title = '启用' + sidebarMenu.title;
                break;
            }
            // 已启用侧边栏编辑
            case 'sidebar': {
                modalEditMenu.id = 'Enable' + modalEditMenu.id;
                modalEditMenu.title = '启用' + modalEditMenu.title;

                sidebarMenu.id = 'Disable' + sidebarMenu.id;
                sidebarMenu.title = '关闭' + sidebarMenu.title;
                break;
            }
            //  未启用弹出或侧边栏编辑
            default: {
                modalEditMenu.id = 'Enable' + modalEditMenu.id;
                modalEditMenu.title = '启用' + modalEditMenu.title;

                sidebarMenu.id = 'Enable' + sidebarMenu.id;
                sidebarMenu.title = '启用' + sidebarMenu.title;
            }
        }
        return menuConfig;
    }

    /**
     * 停用卡片式编辑
     * @param menu 菜单
     * @param dataGridInstance 列表组件实例
     */
    disableCardEdit(menu: ControlContextMenuItem, dataGridInstance: FarrisDesignBaseComponent) {
        dataGridInstance.component.enableEditByCard = 'none';
        dataGridInstance.component.currentViewShowType = 'grid';
        // 停用:  不会将 弹窗组件和VM删除，是为了再次启用后不会丢失组件的改动
        const modalFrameComponent = this.domService.getComponentById(dataGridInstance.component.modalComponentId);
        if (modalFrameComponent) {
            modalFrameComponent.fakeDel = true;
            this.changeFakeDelStateInModalComponent(true, modalFrameComponent.contents);

        }
        this.refreshFormService.refreshFormDesigner.next();
        this.notifyService.success('已' + menu.title);
    }

    createCardEdit(menu: ControlContextMenuItem, dataGridInstance: FarrisDesignBaseComponent) {
        dataGridInstance.component.currentViewShowType = 'grid';
        dataGridInstance.component.enableEditByCard = menu.type;

        let modalComponentId = dataGridInstance.component.modalComponentId;
        if (!modalComponentId) {
            modalComponentId = dataGridInstance.component.id;
            if (modalComponentId.includes('-component')) {
                modalComponentId = modalComponentId.replace('-component', '-modal-component');
            } else {
                modalComponentId = modalComponentId + '-modal';
            }
        }


        // 判断是否已经创建过弹窗组件
        const modalFrameComponent = this.domService.getComponentById(modalComponentId);
        if (modalFrameComponent) {

            if (modalFrameComponent.showType !== menu.type) {
                // 启用过卡片式编辑，需要切换modal或sidebar
                const modifyInfo = {
                    componentId: modalComponentId,
                    showType: dataGridInstance.component.enableEditByCard,
                    gridViewModelId: dataGridInstance.viewModelId,
                    dataSource: dataGridInstance.component.dataSource,
                    oldShowType: modalFrameComponent.showType
                };
                this.modifyCardShowType(modifyInfo);

            }

            modalFrameComponent.fakeDel = false;
            this.changeFakeDelStateInModalComponent(false, modalFrameComponent.contents);

            this.refreshFormService.refreshFormDesigner.next();
            this.notifyService.success('切换成功');
        } else {

            // 没有启用过卡片式编辑
            const modalComponentBuildInfo = new CreateModalCardBuildInfo();
            const gridViewModel = this.domService.getViewModelById(dataGridInstance.viewModelId);
            Object.assign(modalComponentBuildInfo, {
                componentId: modalComponentId,
                componentType: FormComponentType.modalFrame,
                componentName: gridViewModel.name,
                selectedFields: dataGridInstance.component.fields || [],
                gridViewModelId: dataGridInstance.viewModelId,
                gridComponentId: dataGridInstance.componentId,
                dataSource: dataGridInstance.component.dataSource,
                showType: dataGridInstance.component.enableEditByCard
            });

            this.createModalCard(modalComponentBuildInfo);

            dataGridInstance.component.modalComponentId = modalComponentId;

            // 因为涉及到新增【弹出控制器】，所以这里需要获取控制器信息，方便交互面板展示命令数据
            this.webCmdService.checkCommands();

            this.refreshFormService.refreshFormDesigner.next();
            this.notifyService.success('启用成功');
        }
    }

    changeFakeDelStateInModalComponent(flag: boolean, contents: any[]) {

        if (contents && contents.length) {
            contents.forEach(c => {
                if (c.contents) {
                    this.changeFakeDelStateInModalComponent(flag, c.contents);
                }

                if (c.type !== DgControl.ComponentRef.type) {
                    return;
                }
                const modalFormCmp = this.domService.getComponentById(c.component);
                if (modalFormCmp) {
                    modalFormCmp.fakeDel = flag;
                }

            });
        }
    }
    /**
     * 创建一个ModalFrame组件，内部包含Header控件、Form组件、ModalFooter控件
     * @param buildInfo 创建组件所需的构造信息
     */
    private createModalCard(buildInfo: CreateModalCardBuildInfo) {

        this.buildInfo = buildInfo;

        Object.keys(this.btnCommand).forEach(key => {
            this.btnCommand[key] = buildInfo.dataSource + this.btnCommand[key];
        });

        this.createComponentNode();
        this.createViewModeNode();

        this.addPopupCommandToGridViewModel();
    }
    /**
     * 添加ModalFrame组件节点
     */
    private createComponentNode() {
        const componentNode = this.controlService.getControlMetaData(DgControl.Component.type);

        const formComponentRef = this.createFormComponentContents();

        const rootContainer = this.getModalCardContainer(formComponentRef);
        Object.assign(componentNode, {
            id: `${this.buildInfo.componentId}`,
            viewModel: `${this.buildInfo.componentId}-viewmodel`,
            componentType: this.buildInfo.componentType,
            contents: [rootContainer],
            dynamic: true,
            showType: this.buildInfo.showType,
            onInit: this.btnCommand.Load
        });
        this.domService.components.push(componentNode);

    }

    /**
     * 创建Form组件内容:component-section-form-controls
     */
    private createFormComponentContents() {


        let modalFormComponentId = '';
        if (this.buildInfo.componentId.includes('-component')) {
            modalFormComponentId = this.buildInfo.componentId.replace('-component', '-form-component');
        } else {
            modalFormComponentId = this.buildInfo.componentId + '-form-modal';
        }

        // 1、创建section
        const section = this.controlService.getControlMetaData(DgControl.Section.type);
        Object.assign(section, {
            id: 'form-section-' + this.buildInfo.componentId,
            appearance: {
                class: 'f-section-form f-section-in-mainsubcard'
            },
            mainTitle: this.buildInfo.componentName,
            showHeader: false
        });
        // 2、创建form
        const layoutForm = this.controlService.getControlMetaData(DgControl.Form.type);
        const controls = [];
        Object.assign(layoutForm, {
            id: 'form-layout-' + this.buildInfo.componentId,
            appearance: {
                class: 'f-form-layout farris-form farris-form-controls-inline'
            },
            contents: controls
        });
        section.contents = [layoutForm];
        const { selectedFields, gridViewModelId } = this.buildInfo;
        const gridDgViewModel = this.dgVMService.getDgViewModel(gridViewModelId);
        // 3、创建控件
        selectedFields.forEach(gridFieldColumn => {
            const dgVMField = gridDgViewModel.fields.find(dgField => dgField.id === gridFieldColumn.binding.field);
            if (!dgVMField) {
                return;
            }

            const controlMetadata = this.controlCreatorService.createControlBySchemaFeild(dgVMField, 'form-col-4');
            controls.push(controlMetadata);
        });

        // 4、创建form组件节点
        const componentNode = this.controlService.getControlMetaData(DgControl.Component.type);
        Object.assign(componentNode, {
            id: modalFormComponentId,
            viewModel: `${modalFormComponentId}-viewmodel`,
            componentType: 'form-col-4',
            contents: [section]
        });
        this.domService.components.push(componentNode);


        // 5、创建viewModel节点
        const gridViewModel = this.domService.getViewModelById(this.buildInfo.gridViewModelId);
        const viewModelNode = new FormViewModel();
        Object.assign(viewModelNode, gridViewModel, {
            id: `${modalFormComponentId}-viewmodel`,
            code: `${modalFormComponentId}-viewmodel`,
            name: this.buildInfo.componentName,
            commands: [],
            states: [],
            fields: cloneDeep(gridViewModel.fields),
            enableValidation: true
        });
        this.domService.viewmodels.push(viewModelNode);

        // 6、创建组件引用节点
        const componentNodeRef = this.controlService.getControlMetaData(DgControl.ComponentRef.type);
        Object.assign(componentNodeRef, {
            id: `${modalFormComponentId}-ref`,
            component: modalFormComponentId
        });

        return componentNodeRef;

    }

    /**
     * 添加ModalFrame的viewModel节点
     */
    private createViewModeNode(): any {
        const stateMachines = this.domService.module.stateMachines;

        const gridDgViewModel = this.domService.getViewModelById(this.buildInfo.gridViewModelId);

        const viewModelNode = new FormViewModel();
        Object.assign(viewModelNode, gridDgViewModel, {
            id: `${this.buildInfo.componentId}-viewmodel`,
            code: `${this.buildInfo.componentId}-viewmodel`,
            name: this.buildInfo.componentName,
            commands: this.createCommands(this.buildInfo.gridViewModelId, this.buildInfo.gridComponentId, this.buildInfo.componentId),
            states: [],
            fields: [],
            stateMachine: stateMachines && stateMachines.length && stateMachines[0].id,
            enableValidation: true
        });

        this.domService.viewmodels.push(viewModelNode);

        // 在命令构件的引用信息中记录子表的命令对构件方法的引用。
        const webcmds = this.domService.getWebCmds();
        let popupWebcmd = webcmds.find(item => item.id === this.popUpCmpId);
        if (!popupWebcmd) {
            popupWebcmd = {
                id: this.popUpCmpId,
                path: 'igix/Web/WebCmp/bo-webcmp/metadata/webcmd',
                name: 'PopController.webcmd',
                refedHandlers: []
            };
            webcmds.push(popupWebcmd);
        }
        for (const command of viewModelNode.commands) {
            popupWebcmd.refedHandlers.push({ host: command.id, handler: command.handlerName });
        }
    }

    /**
     * 创建弹窗根节点
     */
    private getModalCardContainer(formComponentRef: any) {
        const controlIdPostfix = '-' + this.buildInfo.dataSource + '-modal';

        const viewModelId = `${this.buildInfo.componentId}-viewmodel`;
        this.createModalCardButtons(this.buildInfo.dataSource, viewModelId, controlIdPostfix);



        return {
            id: 'root-layout' + controlIdPostfix,
            type: 'ContentContainer',
            appearance:
            {
                class: 'f-page f-page-card f-page-is-mainsubcard f-page-in-dialog  bg-white'
            },
            size: null,
            contents: [
                {
                    id: 'page-header' + controlIdPostfix,
                    type: 'Header',
                    visible: true,
                    appearance: null,
                    size: null,
                    mainTitle: this.buildInfo.componentName,
                    subTitle: '',
                    showIcon: true,
                    iconName: 'f-icon-page-title-record',
                    iconCls: 'f-text-orna-bill',
                    pgShow: false,
                    pgPreDisabled: true,
                    pgNextDisabled: true,
                    pgPreClick: null,
                    pgNextClick: null,
                    showViewChange: false,
                    viewType: 'dropdown',
                    toolbarCls: 'col-6',
                    toolbarDatas: '',
                    toolbarBtnSize: 'lg',
                    toolbarPopDirection: 'default'
                },
                {
                    id: 'main-container' + controlIdPostfix,
                    type: 'ContentContainer',
                    appearance:
                    {
                        class: 'f-page-main f-utils-overflow-auto'
                    },
                    size: null,
                    contents: [
                        {
                            id: 'like-card-container' + controlIdPostfix,
                            type: 'ContentContainer',
                            appearance:
                            {
                                class: 'f-struct-like-card'
                            },
                            size: null,
                            contents: [formComponentRef],
                            visible: true,
                            draggable: false,
                            isLikeCardContainer: true,
                            isScrollspyContainer: false
                        }
                    ],
                    visible: true,
                    isScrollspyContainer: false,
                    draggable: false
                },
                {
                    id: 'page-footer' + controlIdPostfix,
                    type: 'ModalFooter',
                    visible: true,
                    appearance: null,
                    size: null,
                    toolbarCls: 'col-6',
                    toolbarDatas: null,
                    toolbarBtnSize: 'lg',
                    toolbarPopDirection: 'top'
                }
            ],
            visible: true,
            isScrollspyContainer: false,
            draggable: false
        };

    }

    /**
     * 创建弹窗header和footer按钮
     */
    private createModalCardButtons(dataSource: string, viewModelId: string, controlIdPostfix: string) {

        const modalHeaderControlId = 'page-header' + controlIdPostfix;
        const modalFooterControlId = 'page-footer' + controlIdPostfix;


        this.createModalToolbar(dataSource, modalHeaderControlId, viewModelId, 'Add', '新增');
        this.createModalToolbar(dataSource, modalHeaderControlId, viewModelId, 'Remove', '删除');

        this.createModalToolbar(dataSource, modalFooterControlId, viewModelId, 'Cancel', '取消');
        this.createModalToolbar(dataSource, modalFooterControlId, viewModelId, 'Save', '保存');
        this.createModalToolbar(dataSource, modalFooterControlId, viewModelId, 'SaveAndClose', '保存并关闭');

    }

    private createModalToolbar(dataSource: string, controlId: string, viewModelId: string, buttonType: string, buttonText: string) {

        // 1、创建按钮
        const toolbarItem = this.controlService.getControlMetaData(DgControl.ToolBarItem.type);

        toolbarItem.id = dataSource + buttonType + 'Button';
        toolbarItem.text = buttonText;
        toolbarItem.click = this.btnCommand[buttonType];
        toolbarItem.disable = '!viewModel.stateMachine[\'editable\']';

        if (buttonType === 'Add') {
            toolbarItem.appearance = { class: 'btn-primary' };
        }

        // 2、在DOM中记录按钮结构：toolbar.items.[viewModelId].XXX
        if (!this.domService.module.toolbar.items[viewModelId]) {
            this.domService.module.toolbar.items[viewModelId] = [];
        }
        this.domService.module.toolbar.items[viewModelId].push(toolbarItem);

        // 3、记录控件对按钮的引用信息：toolbar.configs.[showType].[controlId]
        const toolbarConfigs = this.domService.module.toolbar.configs;
        const currentShowType = this.buildInfo.showType;
        if (!toolbarConfigs[currentShowType]) {
            toolbarConfigs[currentShowType] = {
                [controlId]: []
            };
        }
        if (!toolbarConfigs[currentShowType][controlId]) {
            toolbarConfigs[currentShowType][controlId] = [];
        }

        toolbarConfigs[currentShowType][controlId].push(toolbarItem.id);
    }

    /**
     * 创建弹窗组件命令
     * @param gridViewModelId 子表所属viewModel id
     * @param gridComponentId 列表组件id
     * @param modalComponentId  弹窗组件id
     */
    private createCommands(gridViewModelId: string, gridComponentId: string, modalComponentId: string) {
        const idService = new IdService();

        const gridVM = this.domService.getViewModelById(gridViewModelId);
        if (!gridVM || !gridVM.commands) {
            return;
        }

        return [
            {
                id: idService.generate(),
                code: this.btnCommand.Add,
                name: '增加一条子表数据',
                params: [
                    {
                        name: 'action',
                        shownName: '状态机动作',
                        value: 'Create'
                    }
                ],
                handlerName: 'AddItem',
                cmpId: this.popUpCmpId,
                extensions: [],
                isInvalid: false
            },
            {
                id: idService.generate(),
                code: this.btnCommand.Remove,
                name: '删除一条子表数据',
                params: [
                    {
                        name: 'id',
                        shownName: '待删除子表数据的标识',
                        value: `{DATA~/#{${gridComponentId}}${gridVM.bindTo}/id}`
                    }
                ],
                handlerName: 'RemoveItem',
                cmpId: this.popUpCmpId,
                extensions: [],
                isInvalid: false
            },
            {
                id: idService.generate(),
                code: this.btnCommand.Cancel,
                name: '取消',
                params: [
                    {
                        name: 'frameId',
                        shownName: '目标组件',
                        value: modalComponentId
                    },
                    {
                        name: 'id',
                        shownName: '当前数据标识',
                        value: ''
                    }
                ],
                handlerName: 'Cancel',
                cmpId: this.popUpCmpId,
                shortcut: {},
                extensions: [],
                isInvalid: false
            },
            {
                id: idService.generate(),
                code: this.btnCommand.Save,
                name: '确认',
                params: [],
                handlerName: 'Confirm',
                cmpId: this.popUpCmpId,
                shortcut: {},
                extensions: []
            },
            {
                id: idService.generate(),
                code: this.btnCommand.SaveAndClose,
                name: '确认并关闭',
                params: [],
                handlerName: 'ConfirmAndClose',
                cmpId: this.popUpCmpId,
                shortcut: {},
                extensions: []
            },
            {
                id: idService.generate(),
                code: this.btnCommand.LoadAndAdd,
                name: '新增一条数据',
                params: [
                    {
                        name: 'action',
                        shownName: '状态机动作',
                        value: 'Create'
                    }
                ],
                handlerName: 'LoadAndAdd',
                cmpId: this.popUpCmpId,
                shortcut: {},
                extensions: []
            },
            {
                id: idService.generate(),
                code: this.btnCommand.LoadAndEdit,
                name: '编辑当前数据',
                params: [
                    {
                        name: 'action',
                        shownName: '状态机动作',
                        value: 'Edit'
                    }
                ],
                handlerName: 'LoadAndEdit',
                cmpId: this.popUpCmpId,
                shortcut: {},
                extensions: []
            },
            {
                id: idService.generate(),
                code: this.btnCommand.LoadAndView,
                name: '查看一条数据',
                params: [
                    {
                        name: 'action',
                        shownName: '状态机动作',
                        value: 'Cancel'
                    }
                ],
                handlerName: 'LoadAndView',
                cmpId: this.popUpCmpId,
                shortcut: {},
                extensions: []
            },
            {
                id: idService.generate(),
                code: this.btnCommand.Load,
                name: '加载',
                params: [
                    {
                        name: 'commandName',
                        shownName: '待执行方法名称',
                        value: '{UISTATE~/#{' + modalComponentId + '}/action}'
                    },
                    {
                        name: 'frameId',
                        shownName: '目标组件',
                        value: '#{' + modalComponentId + '}'
                    }
                ],
                handlerName: 'Load',
                cmpId: this.popUpCmpId,
                shortcut: {},
                extensions: []
            }
        ];
    }

    /**
     * 列表组件内预置打开弹窗的命令
     */
    private addPopupCommandToGridViewModel() {
        const { gridViewModelId, componentId: modalComponentId, gridComponentId } = this.buildInfo;

        const gridVM = this.domService.getViewModelById(gridViewModelId);
        if (!gridVM || !gridVM.commands) {
            return;
        }

        const idService = new IdService();
        const popupCommands = [{
            id: idService.generate(),
            code: this.btnCommand.PopUpEdit,
            name: '在弹出窗口中编辑数据',
            params: [
                {
                    name: 'mode',
                    shownName: '打开方式',
                    value: this.buildInfo.showType
                },
                {
                    name: 'modalId',
                    shownName: '弹出窗口标识',
                    value: modalComponentId
                },
                {
                    name: 'configs',
                    shownName: '弹出窗口配置',
                    value: this.buildInfo.showType === 'modal' ? '{\"width\":900,\"height\":500}' : '{\"width\":\"60%\"}'
                },
                {
                    name: 'params',
                    shownName: '参数',
                    value: '{\"action\":"' + this.btnCommand.LoadAndEdit + '\"}'
                },
                {
                    name: 'idToEdit',
                    shownName: '待编辑数据的标识',
                    value: '{DATA~/#{' + gridComponentId + '}' + gridVM.bindTo + '/id}'
                }
            ],
            handlerName: 'PopUpAndEdit',
            cmpId: this.popUpCmpId,
            shortcut: {},
            extensions: []
        },
        {
            id: idService.generate(),
            code: this.btnCommand.PopUpAdd,
            name: '弹出窗口并新增数据',
            params: [
                {
                    name: 'mode',
                    shownName: '打开方式',
                    value: this.buildInfo.showType
                },
                {
                    name: 'modalId',
                    shownName: '弹出窗口标识',
                    value: modalComponentId
                },
                {
                    name: 'configs',
                    shownName: '弹出窗口配置',
                    value: this.buildInfo.showType === 'modal' ? '{\"width\":900,\"height\":500}' : '{\"width\":\"60%\"}'
                },
                {
                    name: 'params',
                    shownName: '参数',
                    value: '{\"action\":"' + this.btnCommand.LoadAndAdd + '\"}'
                }
            ],
            handlerName: 'PopUp',
            cmpId: this.popUpCmpId,
            shortcut: {},
            extensions: []
        }];



        // 在命令构件的引用信息中记录子表的命令对构件方法的引用。
        const webcmds = this.domService.getWebCmds();
        let popupWebcmd = webcmds.find(item => item.id === this.popUpCmpId);
        if (!popupWebcmd) {
            popupWebcmd = {
                id: this.popUpCmpId,
                path: 'igix/Web/WebCmp/bo-webcmp/metadata/webcmd',
                name: 'PopController.webcmd',
                refedHandlers: []
            };
            webcmds.push(popupWebcmd);
        }
        popupCommands.forEach(c => {
            gridVM.commands.push(c);
            popupWebcmd.refedHandlers.push({ host: c.id, handler: c.handlerName });
        });


        // 安装PopController的maven包
    }


    /**
     * 切换编辑方式：在弹窗和侧边栏之间切换
     */
    private modifyCardShowType(modifyInfo: {
        componentId: string, showType: string, gridViewModelId: string, dataSource: string, oldShowType: string
    }) {
        const modalFrameComponent = this.domService.getComponentById(modifyInfo.componentId);
        modalFrameComponent.showType = modifyInfo.showType;

        // 1、修改列表组件中预置的打开弹窗的命令：前提是用户没有自行修改过预置命令的编号
        const gridVM = this.domService.getViewModelById(modifyInfo.gridViewModelId);
        if (!gridVM || !gridVM.commands) {
            return;
        }
        const popupAddCommandCode = modifyInfo.dataSource + this.btnCommand.PopUpAdd;
        const popupAddCommand = gridVM.commands.find(command =>
            command.cmpId === this.popUpCmpId && command.handlerName === 'PopUp' && command.code === popupAddCommandCode);
        if (popupAddCommand && popupAddCommand.params) {
            popupAddCommand.params.forEach(param => {
                if (param.name === 'mode') {
                    param.value = modifyInfo.showType;
                }
                if (param.name === 'configs') {
                    param.value = modifyInfo.showType === 'modal' ? '{\"width\":900,\"height\":500}' : '{\"width\":\"60%\"}';
                }
            });
        }

        const popupEditCommandCode = modifyInfo.dataSource + this.btnCommand.PopUpEdit;
        const popupEditCommand = gridVM.commands.find(command =>
            command.cmpId === this.popUpCmpId && command.handlerName === 'PopUpAndEdit' && command.code === popupEditCommandCode);
        if (popupEditCommand && popupEditCommand.params) {
            popupEditCommand.params.forEach(param => {
                if (param.name === 'mode') {
                    param.value = modifyInfo.showType;
                }
                if (param.name === 'configs') {
                    param.value = modifyInfo.showType === 'modal' ? '{\"width\":900,\"height\":500}' : '{\"width\":\"60%\"}';
                }
            });
        }


        // 2、修改按钮：例如将sidebar模式下的头部和底部按钮移动到modal模式下
        const toolbar = this.domService.module.toolbar;
        if (!toolbar || !toolbar.configs || !toolbar.configs[modifyInfo.oldShowType]) {
            return;
        }
        const oldToolbarConfigShowType = toolbar.configs[modifyInfo.oldShowType];
        if (!oldToolbarConfigShowType) {
            return;
        }
        if (!toolbar.configs[modifyInfo.showType]) {
            toolbar.configs[modifyInfo.showType] = {};
        }
        const controlIdPostfix = '-' + modifyInfo.dataSource + '-modal';

        const modalHeaderControlId = 'page-header' + controlIdPostfix;
        const modalFooterControlId = 'page-footer' + controlIdPostfix;


        toolbar.configs[modifyInfo.showType][modalHeaderControlId] = oldToolbarConfigShowType[modalHeaderControlId];
        toolbar.configs[modifyInfo.showType][modalFooterControlId] = oldToolbarConfigShowType[modalFooterControlId];

        delete oldToolbarConfigShowType[modalHeaderControlId];
        delete oldToolbarConfigShowType[modalFooterControlId];

    }

    /**
     * 安装popController所属元数据包
     * @param packageNames 待安装的元数据包
     */
    //  checkAndRestoreMetadataPackages() {
    //     const qdpMetadataPackages = 'Inspur.GS.Gsp.QDP.QdpCmp.mdpkg,Inspur.GS.Gsp.QDP.QdpCommonCmp.mdpkg,Inspur.Gsp.Common.CommonCmp.mdpkg';
    //     const formMetadataPath = this.formBasicService.formMetaBasicInfo.relativePath;

    //     let projPath: string;
    //     return this.metadataService.GetProjPath(formMetadataPath).pipe(
    //         switchMap(path => {
    //             projPath = path;
    //             return this.metadataService.getMavenStatus(projPath);
    //         }),
    //         switchMap(isMaven => {
    //             return this.metadataService.addDependencyAndRestore(projPath, qdpMetadataPackages, isMaven);
    //         })
    //     );
    // }
}
